package fms.webservice.server.mq;

/**
 * Created with IntelliJ IDEA.
 * User: root
 * Date: 14-7-10
 * Time: 上午10:24
 * To change this template use File | Settings | File Templates.
 */
import fms.webservice.server.util.MqUtil;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

import javax.jms.*;

public class ActivemqSender implements ISender {

    private Logger logger = Logger.getLogger(ActivemqSender.class);
    private String user = ActiveMQConnection.DEFAULT_USER;
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private String url = MqUtil.getConf("/mq.properties").getProperty("url");
    private String subject = MqUtil.getConf("/mq.properties").getProperty("subject");
    private String subjectTopic = MqUtil.getConf("/mq.properties").getProperty("subjectTopic");
    private Destination destination = null;
    private Connection connection = null;
    private Session session = null;
    private MessageProducer producer = null;

    // 初始化(使用Spring中的jmsTemplate进行ActiveMQ的整合，就可以省略下面手动创建连接、会话的过程)
    private void initialize() throws JMSException, Exception {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                user, password, url);
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        if(subject.equals("") || subject == null)
            destination = session.createTopic(subjectTopic);
        else
            destination = session.createQueue(subject);
        producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    // 发送消息
    public void send(String message){
        try{
            initialize();
            TextMessage msg = session.createTextMessage(message);
            connection.start();
            System.out.println("Producer:->Sending message: " + message);
            producer.send(msg);
            System.out.println("Producer:->Message sent complete!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 关闭连接
    public void close() throws JMSException {
        System.out.println("Producer:->Closing connection");
        if (producer != null)
            producer.close();
        if (session != null)
            session.close();
        if (connection != null)
            connection.close();
    }

}
